﻿
//vue viewmodel基类
 function VueViewModelBase() {
     var me = this;

     me.orgTreeUrl = "";
     me.tableListUrl = "";
     me.addUrl = "";
     me.delUrl = "";
     me.tabObj = "";//table对象
     me.selections = null;//获取选中行对象
     me.addOp = true;


     me.addMonitor = function () {

     }
     me.addMonitorObj = function (targetObj,monitorObj) {
         if (monitorObj != null && monitorObj != undefined) {
             for (var key in monitorObj) {
                 //bootstrap table 对象首字母是小写的和数据库字段不匹配，在此转换
                 var oldKey = key;
                 key = key.substring(0, 1).toUpperCase() + key.substring(1);
                 vueModel.$set(targetObj, key, monitorObj[oldKey]);
             }
         }
     }
    me.add = function () {
        //alert("parentAddOpen");
     }
    
    me.edit = function () {
        if (vueModel.selectedData) {
            var selectRows = me.selections;

            var lastSelectObj = selectRows[selectRows.length - 1];


            me.addMonitor(lastSelectObj);
        } else {
            $dh.msg(_SelectADataMsg);//请选择一条数据
        }
    }
    me.save = function (callback) {
        if (!$('#form1').formValid()) {
            return false;
            callback(false);
        }

        var model = vueModel.$data.entityObj;

        //执行成功
        $dh.post(me.addUrl, model, function (result) {
            if (result.Status == ResultStatus.OK) {

                callback(result, true);

            } else {
                callback(result, false);

            }


        });

        //callback(true);
    }
    me.delete = function (callback) {
        if (!vueModel.selectedData) {

            $dh.msg(_SelectADataMsg); //请选择一条数据
        } else {
            var selectRows = me.selections;
            var ids = [];
            for (var idIndex = 0; idIndex < selectRows.length; idIndex++) {
                ids.push(selectRows[idIndex].id);
            }

            $dh.confirm(_deleteRemand, function () {
                //确认删除
                $dh.post(me.delUrl, { ids: ids }, function (result) {
                    if (result.Status == ResultStatus.OK) {

                        callback(result, true);
                        
                    } else {
                        callback(result, false);

                    }
                });

            });

        }
        
        //callback(true);
    }
    me.search = function () {
        me.tabObj.bootstrapTable('refresh');
    }
    me.init = function () {
    }
    me.initTableList = function (options) {
        me.initList(options);
    }
    me.bindTree = function (url,targetElement) {
        var setting = {

            view: { selectedMulti: false },
            data: {
                key: {
                    name: 'text',
                    title: 'text'
                },
                simpleData: {
                    enable: true,
                    idKey: 'id',
                    pIdKey: 'parentId',
                    rootPId: 'null'
                }
            },
            callback: {
                onClick: function (event, treeId, treeNode) {
                    //alert(treeId + ":" + treeNode.id);
                    vueModel.treeId = treeNode.id;

                    me.search();
                }
            }
        };
        $.getJSON(url, function (json) {
            var zTreeObj = $.fn.zTree.init($("#" + targetElement), setting, json);

            //展开一级节点
            var treeObj = $.fn.zTree.getZTreeObj(targetElement);
            var rootNode = treeObj.getNodeByParam("id", "00000000-0000-0000-0000-000000000000", null);
            treeObj.expandNode(rootNode, true, false, true);

            //展开所有节点
            //zTreeObj.expandAll(false);


        });
    }

    me.refreshTree = function (url, targetElement) {
        var treeObj = $.fn.zTree.getZTreeObj(targetElement);
        treeObj.destroy();
        me.bindTree(url, targetElement);
    }

    me.initList = function (options) {
        var defaults = {
            url: me.tableListUrl,
            method: 'get',                      //请求方式（*）
            dataType: 'json',
            contentType: "application/x-www-form-urlencoded",
            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            sortable: true,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10,20,50],         //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: true,
            showColumns: true,                  //是否显示所有的列
            showRefresh: false,                  //是否显示刷新按钮
            showFilter:false,                    //是否显示filter
            minimumCountColumns: 1,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            //height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "Id",                     //每一行的唯一标识，一般为主键列
            showToggle: true,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            queryParams: function (params) {
                //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                
                var temp = {
                    rows: params.limit,                         //页面大小
                    page: (params.offset / params.limit) + 1,   //页码
                    queryKey: vueModel.queryKey,
                    treeId: vueModel.treeId
                };
                return temp;
            },
            queryParamsType: "limit",
            columns: [{
                checkbox: true
            }],
            //filter: false,
            filterControl:false,
            //filterTemplate: {
            //},
            onLoadSuccess: function (data) {
                var data = data;
                //$dh.RespondStatusCode(data);
            },
            onLoadError: function (status) {
                var sta = status;
                $dh.RespondStatusCode(sta);
            },
            onClickRow: function (row, $element) {
                me.setSelectedData();
            },
            onCheck: function (row) {
                me.setSelectedData();
            },
            onUncheck: function (row) {
                me.setSelectedData();

            },
            onCheckAll: function (rows) {
                me.setSelectedData();
            },
            onUncheckAll: function (rows) {
                me.setSelectedData();
            }
        };
        var options = $.extend(defaults, options);

        var tableObj = me.tabObj.bootstrapTable({
            url: options.url,
            method: options.method,
            dataType: options.dataType,
            contentType: options.contentType,
            toolbar: options.toolbar,
            striped: options.striped,
            singleSelect: options.singleSelect,         //是否启用单选功能
            cache: options.cache,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: options.pagination,                   //是否显示分页（*）
            sortable: options.sortable,                     //是否启用排序
            sortOrder: options.sortOrder,                   //排序方式
            sidePagination: options.sidePagination,           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: options.pageNumber,                       //初始化加载第一页，默认第一页
            pageSize: options.pageSize,                       //每页的记录行数（*）
            pageList: options.pageList,        //可供选择的每页的行数（*）
            search: options.search,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: options.strictSearch,
            showColumns: options.showColumns,                  //是否显示所有的列
            showRefresh: options.showRefresh,                  //是否显示刷新按钮
            showFilter: options.showFilter,                    //是否显示过滤
            minimumCountColumns: options.minimumCountColumns,             //最少允许的列数
            clickToSelect: options.clickToSelect,                //是否启用点击选中行
            //height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: options.uniqueId,                     //每一行的唯一标识，一般为主键列
            showToggle: options.showToggle,                    //是否显示详细视图和列表视图的切换按钮
            cardView: options.cardView,                    //是否显示详细视图
            detailView: options.detailView,                   //是否显示父子表
            showExport: options.showExport,                   //是否显示导出功能
            exportDataType: options.exportDataType,           //导出类型
            //得到查询的参数
            queryParams: options.queryParams,
            queryParamsType: options.queryParamsType,
            columns: options.columns,
            //filter: options.filter,                          //是否显示过滤
            filterControl: options.filterControl,
            filterTemplate: options.filterTemplate,
            onLoadSuccess: options.onLoadSuccess,
            onLoadError: options.onLoadError,
            onClickRow: options.onClickRow,
            onCheck: options.onCheck,
            onUncheck: options.onUncheck,
            onCheckAll: options.onCheckAll,
            onUncheckAll: options.onUncheckAll

        });

    }

    //设置是否获取行状态
    me.setSelectedData = function () {
        var selectRows = me.tabObj.bootstrapTable('getSelections');
        me.selections = selectRows;

        if (selectRows.length <= 0) {
            vueModel.selectedData = false;
        } else {
            //待处理
            vueModel.selectedData = true;
        }
    }

    me.uncheckAll = function () {
        me.tabObj.bootstrapTable('uncheckAll');
    }

   
    /*
     * obj 当前操作html对象
     * id  行绑定对象Id
     * opEnableUrl 启用功能url
     * opDisAbleUrl 禁用功能Url
     */
    me.onEnabledClick = function (obj,index, id,opEnableUrl,opDisAbleUrl, e) {
        e.stopPropagation();//行内编辑事件，禁止事件传递（不触发bootstrap table 的clickrow事件）
        $dh.post(opEnableUrl, { id: id }, function (result) {
            if (result.Status == ResultStatus.OK) {
                //刷新
                //vueModel.search();
                $dh.msg("启用成功");

                var disabledEle = '<a href="javascript:void(0)" onclick="_vmBase.onDisabledClick(this,' + index + ',\'' + id + '\',\'' + opEnableUrl + '\',\'' + opDisAbleUrl +'\',event)">' + _disabledStr + '</a>';
                var parentObj = $(obj).parent();
                //parentObj.html("");
                parentObj.html(disabledEle);

                var enabledLabel = '<span class="label label-success" id="' + id + '"><i class="fa fa-unlock"></i>' + _enabledStr + '</span>';
                var parentSb = parentObj.prev();
                parentSb.html(enabledLabel);
            }

        });

    }

     /*
     * obj 当前操作html对象
     * id  行绑定对象Id
     * opEnableUrl 启用功能url
     * opDisAbleUrl 禁用功能Url
     */
    me.onDisabledClick = function (obj,index, id, opEnableUrl, opDisAbleUrl, e) {
        e.stopPropagation(); //行内编辑事件，禁止事件传递（不触发bootstrap table 的clickrow事件）
        $dh.post(opDisAbleUrl, { id: id }, function (result) {
            if (result.Status == ResultStatus.OK) {
                //刷新
                //vueModel.search();
                $dh.msg("禁用成功");

                var enabledEle = '<a href="javascript:void(0)" onclick="_vmBase.onEnabledClick(this,' + index + ',\'' + id + '\',\'' + opEnableUrl + '\',\'' + opDisAbleUrl +'\',event)">' + _enabledStr + '</a>';
                var parentObj = $(obj).parent();
                parentObj.html(enabledEle);

                var disabledLabel = '<span class="label label-default" id="' + id + '"><i class="fa fa-lock"></i> ' + _disabledStr + '</span>';
                var parentSb = parentObj.prev();
                parentSb.html(disabledLabel);



            }

        });
    }
    
   
};

var _vmBase;

//注册组件：模态弹窗
Vue.component('modal-dialog', {
    template: `
    <div class="modal fade in"  style="display:block" id="myModal"  role="dialog" aria-labelledby="myModalLabel" aria-hidden="false" data-keyboard="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header" style=" cursor: move">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true" v-on:click="hideModal">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">{{title}}</h4>
                </div>
                <div class="modal-body">
                 <slot name="modal-body">
                        
                 </slot>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal" v-on:click="hideModal"><i class="fa fa-close" style="margin-right: 5px;"></i>{{btnclose}}</button>
                    <button type="button" class="btn btn-primary" v-on:click="saveModel"><i class="fa fa-check" style="margin-right: 5px;"></i>{{btnsubmit}}</button>
                </div>
            </div>
        </div>
    </div>
    `,
    props: ['title','entity','btnclose','btnsubmit'],
    methods: {
        hideModal: function () {
            vueModel.hideModal();
        },
        saveModel: function () {

            vueModel.save();
        }
    }
})



var modalData = {
    showDialog: false,
    showDialogTypeAdd:true,
    modalTitle: '模态窗',
    queryKey: '',
    treeId:'',//所在Tree Id
    entityObj: {},
    selectedData: false,
    btnClose: '关闭',
    btnSubmit: '确认提交',
    status: true, //状态
    //checkEnabled: selectedData && status,
    //checkDisabled: selectedData && !status
    
}

Vue.filter('DateFormater', function (value) {
    return DateFormat(value);//时间过滤器适用于{{}},v-bind 不适用v-model
})

var vueModel = new Vue({
    el: '#appModel',
    data: modalData,
    methods: {
        showModal: function () {
            if (!this.selectedData && !this.showDialogTypeAdd) {
                return false;
            }

            this.showDialog = true;

            //新增还是编辑
            var operType = _opAddStr;
            var dataObj = this.entityObj;
            if (dataObj.Id != null && dataObj.Id != undefined && dataObj.Id!="") {
                operType = _opEditStr;
                _vmBase.addOp = false;//当前操作 编辑
            } else {
                operType = _opAddStr;
                _vmBase.add();

                _vmBase.addOp = true; //当前操作 新增

            }
            this.modalTitle = operType;//弹窗标题文字
            this.btnClose = _btnClose; //弹窗关闭文字
            this.btnSubmit = _btnSubmit; //弹窗提交文字
        },
        hideModal: function () {
            //vueModel.entityObj = {};//清空绑定监听
            _vmBase.addMonitor();//重新初始化绑定监听

            this.showDialog = false;

            vueModel.selectedData = false; //删除保留的已选择状态，否则新增有问题

            _vmBase.uncheckAll(); //关闭窗体就取消所有选择的行
            
        },
        search: function () {
            _vmBase.search();
        },
        add: function () {
            this.showDialogTypeAdd = true;
            this.showModal();
        },
        edit: function () {
            this.showDialogTypeAdd = false;
            _vmBase.edit();
            this.showModal();
        },
        save: function () {            

            _vmBase.save(function (result,data) {
                if (data) {
                    vueModel.hideModal();
                    //刷新
                    vueModel.search();
                    $dh.msg(result.Msg);
                    

                } else {
                    $dh.alert(result.Msg);
                }
            });
        },
        del: function () {
            _vmBase.delete(function (result,data) {
                if (data) {
                    //刷新
                    vueModel.search();

                    $dh.msg(result.Msg);

                    vueModel.selectedData = false; //删除条目后，删除保留的已选择状态，否则新增有问题
                } else {
                    $dh.alert(result.Msg);
                }
                
            });
        }
        

    }

});



/**
 * 格式化时间
 * @param {any} input
 */
function DateFormat(input) {
    if (input == null || input == undefined || input.length <= 0) {
        return '';
    } else {
        var d = new Date(input);

        var year = d.getFullYear();
        var month = d.getMonth() + 1;
        var day = d.getDate() < 10 ? '0' + d.getDate() : '' + d.getDate();
        var hour = d.getHours();
        var minutes = d.getMinutes();
        var seconds = d.getSeconds();
        return year + '-' + month + '-' + day
    }
}
